<template>
	<view class="recharge-page">
		<!-- 余额卡片 -->
		<view class="balance-card">
			<view class="balance-label">账户余额（元）</view>
			<view class="balance-value">{{ balance }}</view>
		</view>

		<!-- 选择充值金额 -->
		<view class="section-title">选择充值金额</view>
		<view class="amount-list">
			<view
				v-for="item in presetList"
				:key="item.value"
				class="amount-item"
				:class="{ active: selectedAmount === item.value }"
				@tap="selectAmount(item.value)"
			>
				<view class="amount">¥{{ item.value }}</view>
				<view class="gift">赠送{{ item.gift }}元</view>
			</view>
		</view>

		<!-- 自定义金额输入 -->
		<view class="custom-amount-box">
			<input
				class="custom-amount-input"
				type="number"
				v-model="customAmount"
				placeholder="输入自定义金额"
				@focus="selectAmount(null)"
			/>
		</view>

		<!-- 充值说明 -->
		<view class="desc-title">充值说明</view>
		<view class="desc-list">
			<view class="desc-item">1、本次充值可用于平台上消费，各地区站点皆可使用。</view>
			<view class="desc-item">2、若遇到充值未到账，请联系客服。</view>
		</view>

		<!-- 充值按钮 -->
		<button class="recharge-btn" @tap="handleRecharge">充值</button>

		<!-- 支付弹窗 -->
		<view v-if="paymentPopupVisible" class="modal">
			<view class="modal-mask" @tap="closePaymentPopup"></view>
			<view class="payment-popup-wrapper">
				<view class="payment-popup" :animation="popupAnimation">
					<view class="popup-header">
						<text class="close-btn" @click="closePaymentPopup">×</text>
						<text class="password-btn">使用密码</text>
					</view>
					<view class="amount-section">
						<text class="merchant-name">充值金额</text>
						<view class="currency-amount-wrapper">
							<text class="currency">¥</text>
							<text class="amount">{{ getRechargeAmount() }}</text>
						</view>
					</view>
					<view class="divider-line"></view>
					<view class="payment-method-section">
						<view class="method-header">
							<view class="label">付款方式</view>
							<view class="change-method">
								<text>更改</text>
								<text class="arrow">></text>
							</view>
						</view>
						<view class="method-item">
							<image src="/static/tabbar/零钱通.png" class="method-icon"></image>
							<view class="method-details">
								<text class="method-name">零钱通</text>
								<text class="method-provider">由腾安公司提供货币基金销售服务</text>
							</view>
							<text class="checkmark">✔</text>
						</view>
					</view>
					<view class="popup-footer">
						<button class="pay-btn" @click="confirmPayment">支付</button>
					</view>
				</view>
			</view>
		</view>

		<!-- 密码输入弹窗 -->
		<view v-if="passwordPopupVisible" class="modal">
			<view class="modal-mask" @tap="closePayPasswordPopup"></view>
			<view class="payment-popup-wrapper">
				<view class="pay-password-popup" :animation="popupAnimation">
					<view class="popup-header">
						<text class="close-btn" @tap="closePayPasswordPopup">×</text>
						<text class="face-btn">使用面容</text>
					</view>
					<view class="popup-amount">
						<text class="merchant">充值金额</text>
						<view class="currency-amount-row">
							<text class="currency">¥</text>
							<text class="amount">{{ getRechargeAmount() }}</text>
						</view>
					</view>
					<view class="popup-method">
						<view class="method-label">付款方式</view>
						<view class="method-change">
							<text>更改</text>
							<text class="arrow">></text>
						</view>
						<view class="method-item">
							<image src="/static/tabbar/建设银行.png" class="method-icon"></image>
							<view class="method-info">
								<text class="method-name">建设银行储蓄卡</text>
								<text class="method-desc">**** **** **** 2779</text>
							</view>
							<text class="checkmark">✔</text>
						</view>
					</view>
					<view class="popup-password">
						<view class="password-box">
							<view v-for="(cell, index) in 6" :key="index" class="pwd-cell">
								<view v-if="password.length > index" class="dot"></view>
							</view>
						</view>
					</view>
					<view class="popup-keyboard">
						<view v-for="(row, rowIndex) in keyboardRows" :key="rowIndex" class="keyboard-row">
							<view v-for="(key, keyIndex) in row" :key="keyIndex" :class="['key-btn', key === 'del' ? 'del' : (key === '' ? 'empty' : '')]" @click="onKeyClick(key)">{{ key }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 支付成功弹窗 -->
		<view v-if="successPopupVisible" class="modal">
			<view class="modal-mask" @tap="closePaySuccessPopup"></view>
			<view class="payment-popup-wrapper">
				<view class="pay-success-popup" :animation="popupAnimation">
					<view class="success-top-bar">
						<image src="/static/tabbar/微信支付.png" class="success-icon"></image>
						<text class="success-text">支付成功</text>
					</view>
					<view class="success-amount-block">
						<text class="success-merchant">充值金额</text>
						<view class="success-amount-row">
							<text class="currency">¥</text>
							<text class="amount">{{ getRechargeAmount() }}</text>
						</view>
					</view>
					<view class="success-bottom-block">
						<button class="success-btn" @tap="closePaySuccessPopup">完成</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { userApi } from '../../api/index.js'

const balance = ref(168.30)
const presetList = [
	{ value: 70, gift: 3 },
	{ value: 100, gift: 10 },
	{ value: 200, gift: 30 }
]
const selectedAmount = ref(presetList[0].value)
const customAmount = ref('')
let originBalance = 0

// 进入页面时接收url参数balance
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	if (currentPage && currentPage.options && currentPage.options.balance) {
		balance.value = Number(currentPage.options.balance)
		originBalance = Number(currentPage.options.balance)
	} else {
		originBalance = balance.value
	}
})

// 获取实际充值金额（自定义优先）
const getRechargeAmount = () => {
	if (customAmount.value && Number(customAmount.value) > 0) {
		return Number(customAmount.value)
	}
	return selectedAmount.value
}

// 获取赠送金额（仅预设金额有赠送，自定义为0）
const getGiftAmount = () => {
	if (customAmount.value && Number(customAmount.value) > 0) {
		return 0
	}
	const preset = presetList.find(item => item.value === selectedAmount.value)
	return preset ? Number(preset.gift) : 0
}

// 弹窗相关状态
const paymentPopupVisible = ref(false)
const passwordPopupVisible = ref(false)
const successPopupVisible = ref(false)
const popupAnimation = ref(null)
const animation = ref(null)
const password = ref('')

// 数字键盘布局
const keyboardRows = [
	['1', '2', '3'],
	['4', '5', '6'],
	['7', '8', '9'],
	['', '0', 'del']
]

const selectAmount = (val) => {
	selectedAmount.value = val
	if (val !== null) customAmount.value = ''
}

// 关闭支付弹窗
const closePaymentPopup = () => {
	animation.value.translateY('100%').step()
	popupAnimation.value = animation.value.export()
	setTimeout(() => {
		paymentPopupVisible.value = false
	}, 200)
}

// 支付弹窗内点击支付，弹出密码输入弹窗
const confirmPayment = () => {
	closePaymentPopup()
	passwordPopupVisible.value = true
	nextTick(() => {
		animation.value.translateY(0).step()
		popupAnimation.value = animation.value.export()
	})
}

// 关闭密码弹窗
const closePayPasswordPopup = () => {
	animation.value.translateY('100%').step()
	popupAnimation.value = animation.value.export()
	setTimeout(() => {
		passwordPopupVisible.value = false
		password.value = ''
	}, 200)
}

// 处理键盘输入
const onKeyClick = async (key) => {
	if (key === 'del') {
		if (password.value.length > 0) {
			password.value = password.value.slice(0, -1)
		}
	} else if (key && password.value.length < 6) {
		password.value += key
		if (password.value.length === 6) {
			// 充值：将本地已有余额+充值金额+赠送金额累加后发送
			const token = uni.getStorageSync('token')
			const recharge = getRechargeAmount()
			const gift = getGiftAmount()
			const newBalance = Number(originBalance) + Number(recharge) + Number(gift)
			try {
				uni.showLoading({ title: '余额更新中...' })
				const res = await userApi.updateUserBalance(token, newBalance)
				uni.hideLoading()
				if (res.code === 200) {
					passwordPopupVisible.value = false
					successPopupVisible.value = true
					balance.value = newBalance
					originBalance = newBalance
				} else {
					uni.showToast({ title: res.msg || '余额更新失败', icon: 'none' })
					password.value = ''
				}
			} catch (e) {
				uni.hideLoading()
				uni.showToast({ title: '余额更新失败', icon: 'none' })
				password.value = ''
			}
		}
	}
}

// 关闭支付成功弹窗
const closePaySuccessPopup = () => {
	successPopupVisible.value = false
	selectedAmount.value = presetList[0].value
	customAmount.value = ''
}

// 点击充值按钮，直接弹出支付弹窗
const handleRecharge = () => {
	let amount = getRechargeAmount()
	if (!amount || amount <= 0) {
		uni.showToast({ title: '请输入有效充值金额', icon: 'none' })
		return
	}
	paymentPopupVisible.value = true
	nextTick(() => {
		animation.value = uni.createAnimation({ duration: 150, timingFunction: 'ease-out' })
		animation.value.translateY(0).step()
		popupAnimation.value = animation.value.export()
	})
}
</script>

<style lang="scss" scoped>
.recharge-page {
	min-height: 100vh;
	background: #fff;
	padding: 0 24rpx 32rpx 24rpx;
}
.balance-card {
	background: #057393;
	border-radius: 16rpx;
	padding: 32rpx 0 24rpx 32rpx;
	margin-top: 32rpx;
	margin-bottom: 32rpx;
	color: #fff;
	.balance-label {
		font-size: 24rpx;
		opacity: 0.8;
		margin-bottom: 12rpx;
	}
	.balance-value {
		font-size: 48rpx;
		font-weight: bold;
		letter-spacing: 2rpx;
	}
}
.section-title {
	font-size: 28rpx;
	color: #222;
	font-weight: 500;
	margin-bottom: 24rpx;
}
.amount-list {
	display: flex;
	gap: 20rpx;
	margin-bottom: 24rpx;
	.amount-item {
		flex: 1;
		background: #f7f8fa;
		border-radius: 12rpx;
		padding: 24rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		border: 2rpx solid transparent;
		transition: border-color 0.2s;
		.amount {
			font-size: 32rpx;
			font-weight: 600;
			color: #222;
			margin-bottom: 8rpx;
		}
		.gift {
			font-size: 22rpx;
			color: #057393;
		}
		&.active {
			border-color: #057393;
			background: #e6f6fa;
		}
	}
}
.custom-amount-box {
	background: #f7f8fa;
	border-radius: 12rpx;
	padding: 0 24rpx;
	margin-bottom: 32rpx;
	display: flex;
	align-items: center;
	.custom-amount-input {
		width: 100%;
		height: 80rpx;
		border: none;
		background: transparent;
		font-size: 28rpx;
		color: #057393;
		outline: none;
	}
}
.desc-title {
	font-size: 26rpx;
	color: #888;
	margin-bottom: 8rpx;
}
.desc-list {
	margin-bottom: 48rpx;
	.desc-item {
		font-size: 22rpx;
		color: #888;
		line-height: 1.8;
	}
}
.recharge-btn {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	background: #0593d3;
	color: #fff;
	font-size: 30rpx;
	border-radius: 40rpx;
	margin-top: 24rpx;
	font-weight: 600;
	letter-spacing: 2rpx;
	border: none;
}
.modal {
	position: fixed;
	top: 0; left: 0; right: 0; bottom: 0;
	z-index: 999;
	
	.modal-mask {
		position: absolute;
		top: 0; left: 0; right: 0; bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		backdrop-filter: blur(1px);
	}
	
	.payment-popup-wrapper {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}
	
	.payment-popup {
		width: 100%;
		background-color: #ffffff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		transform: translateY(100%);
	}
}
.payment-popup {
	.popup-header { display: flex; justify-content: space-between; align-items: center; padding: 10rpx 30rpx 20rpx; .close-btn { font-size: 40px; color: #999; } .password-btn { font-size: 28rpx; color: #687597; } }
	.amount-section { display: flex; flex-direction: column; justify-content: center; align-items: center; padding: 10rpx 0; .merchant-name { font-size: 28rpx; color: #888; margin-bottom: 20rpx; } .currency-amount-wrapper { display: flex; align-items: flex-end; .currency { font-size: 48rpx; font-weight: bold; color: #333; position: relative; top: -35rpx; } .amount { font-size: 80rpx; font-weight: bold; color: #333; margin-left: 10rpx; } } }
	.divider-line { height: 1rpx; background-color: #eee; margin: 20rpx 0; }
	.payment-method-section { padding: 0 30rpx; margin-bottom: 40rpx; .method-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20rpx; .label { font-size: 26rpx; color: #999; } .change-method { display: flex; align-items: center; font-size: 26rpx; color: #999; .arrow { margin-left: 10rpx; font-weight: bold; } } } .method-item { display: flex; align-items: center; background: #FFF8E6; border-radius: 12rpx; padding: 40rpx 30rpx; position: relative; .method-icon { width: 25rpx; height: 25rpx; margin-right: 20rpx; position: relative; top: -7px; } .method-details { flex: 1; display: flex; flex-direction: column; justify-content: center; .method-name { font-size: 26rpx; color: #888; margin-bottom: 10px; } .method-provider { font-size: 22rpx; color: #888; } } .checkmark { font-size: 36rpx; color: #07c160; margin-left: 20rpx; position: relative; left: -10px; } } }
	.popup-footer { padding: 20rpx 30rpx; .pay-btn { background-color: #07c160; color: #ffffff; font-size: 32rpx; height: 90rpx; line-height: 90rpx; border-radius: 20rpx; width: 50%; margin-top: 20px; margin-bottom: 20px; } }
}
.pay-password-popup {
	background: #fff;
	border-top-left-radius: 32rpx;
	border-top-right-radius: 32rpx;
	padding-bottom: env(safe-area-inset-bottom);
	box-shadow: 0 -8rpx 32rpx rgba(0,0,0,0.08);
	position: fixed;
	bottom: -33px;
	width: 100%;
	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15rpx 32rpx 0 32rpx;
		.close-btn {
			font-size: 40px;
			color: #333;
		}
		.face-btn {
			font-size: 28rpx;
			color: #576b95;
		}
	}
	.popup-amount {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 16rpx;
		.merchant {
			font-size: 28rpx;
			color: #888;
			margin-bottom: 8rpx;
		}
		.currency-amount-row {
			display: flex;
			align-items: baseline;
			justify-content: center;
			.currency {
				font-size: 22px;
				font-weight: 600;
				color: #222;
				margin-right: 2px;
				position: relative;
				top: -2px;
			}
			.amount {
				font-size: 40px;
				font-weight: 600;
				color: #222;
				line-height: 1;
			}
		}
	}
	.popup-method {
		margin: 0 32rpx 24rpx 32rpx;
		.method-label {
			font-size: 24rpx;
			color: #999;
			margin-bottom: 8rpx;
		}
		.method-change {
			position: absolute;
			right: 48rpx;
			top: 0;
			font-size: 24rpx;
			color: #999;
			.arrow { margin-left: 4rpx; }
		}
		.method-item {
			display: flex;
			align-items: center;
			background: #EAF3FC;
			border-radius: 16rpx;
			padding: 37rpx 20rpx;
			margin-top: 25rpx;
			.method-icon {
				width: 50rpx;
				height: 40rpx;
				margin-right: 16rpx;
			}
			.method-info {
				flex: 1;
				display: flex;
				flex-direction: column;
				.method-name {
					font-size: 28rpx;
					color: #333;
				}
				.method-desc {
					font-size: 22rpx;
					color: #888;
				}
			}
			.checkmark {
				font-size: 36rpx;
				color: #07c160;
				margin-left: 12rpx;
			}
		}
		position: relative;
	}
	.popup-password {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 32rpx 0 0 0;
		.password-box {
			display: flex;
			gap: 16rpx;
			.pwd-cell {
				width: 74rpx;
				height: 74rpx;
				border-radius: 8rpx;
				background: #F2F2F2;
				display: flex;
				align-items: center;
				justify-content: center;
				margin: 10px 0px;
				.dot {
					width: 16rpx;
					height: 16rpx;
					background: #222;
					border-radius: 50%;
				}
			}
		}
	}
	.popup-keyboard {
		background: #EDEDED;
		padding-bottom: env(safe-area-inset-bottom);
		margin-top: 10px;
		border-top: 1px solid #EDEDED;
		.keyboard-row {
			display: flex;
			width: 100%;
			.key-btn {
				flex: 1;
				height: 55px;
				background: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28px;
				color: #222;
				border-right: 1px solid #e5e5e5;
				border-bottom: 1px solid #e5e5e5;
				box-sizing: border-box;
				border-radius: 0;
				&.del {
					background: #EDEDED;
					color: #222;
				}
				&.empty {
					background: #EDEDED;
					border-right: none;
					border-bottom: none;
				}
			}
			.key-btn:last-child {
				border-right: none;
			}
		}
		.keyboard-row:last-child .key-btn {
			border-bottom: none;
		}
	}
}
.pay-success-popup {
	position: fixed;
	left: 0; right: 0; top: 0; bottom: 0;
	width: 100vw; height: 100vh;
	background: #fff;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: flex-start;
	z-index: 9999;
	.success-top-bar {
		margin-top: 25px;
		margin-bottom: 50px;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
		.success-icon {
			width: 20px;
			height: 20px;
			margin-bottom: 0;
		}
		.success-text {
			color: #07c160;
			font-size: 15px;
			font-weight: 500;
			margin-left: 8px;
			margin-bottom: 0;
		}
	}
	.success-amount-block {
		margin-top: 16px;
		display: flex;
		flex-direction: column;
		align-items: center;
		.success-merchant {
			color: #888;
			font-size: 15px;
			margin-bottom: 10px;
		}
		.success-amount-row {
			display: flex;
			align-items: baseline;
			justify-content: center;
			.currency {
				font-size: 30px;
				font-weight: 600;
				color: #222;
				margin-right: 2px;
				position: relative;
				top: -9px;
			}
			.amount {
				font-size: 40px;
				font-weight: 600;
				color: #222;
				line-height: 1;
			}
		}
	}
	.success-progress {
		width: 80vw;
		margin: 32px 0 48px 0;
		display: flex;
		justify-content: center;
		.progress-bar {
			width: 100%;
			height: 6px;
			background: #f5f5f5;
			border-radius: 3px;
			overflow: hidden;
			.progress-inner {
				width: 30px;
				height: 100%;
				background: #fa5151;
				border-radius: 3px;
			}
		}
	}
	.success-bottom-block {
		width: 100vw;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: absolute;
		bottom: 60px;
		left: 0;
		.success-btn {
			position: relative;
			top: -40px;
			width: 40vw;
			height: 44px;
			background: #f5f5f5;
			color: #222;
			font-size: 15px;
			border-radius: 5px;
			border: none;
			margin: 0 auto;
			text-align: center;
			line-height: 44px;
		}
	}
}
</style>
